<template>
  <div class="app-container">
    <h3>任务编辑</h3>

    <el-form :model="form" :rules="rules" ref="form" label-width="120px">

      <el-form-item prop="taskName" label="任务名称">
        <el-input v-model="form.taskName"></el-input>
      </el-form-item>

      <el-form-item prop="taskTypeId" label="任务类型">
        <el-cascader :props="{ label: 'typeName', value: 'id' }" v-model="typeIds" :options="options"
          @change="handleTypeChange"></el-cascader>
      </el-form-item>

      <el-form-item prop="taskDistrict" label="任务地区">
        <el-select v-model="form.taskDistrict">
          <el-option :label="item.label" :value="item.label" v-for="item in districts"></el-option>
        </el-select>
      </el-form-item>

      <!-- <el-form-item prop="cover" label="封面">
        <el-upload class="avatar-uploader" action="" :auto-upload="false" :show-file-list="false"
          :on-change="handleCoverChange" name="img">
          <img v-if="form.cover" :src="form.cover" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item> -->

      <el-form-item prop="cover" label="封面">
        <el-upload class="avatar-uploader" action="" :auto-upload="false" :show-file-list="false"
          :on-change="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
          <img v-if="form.cover" :src="form.cover" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>

      <el-form-item prop="latitude" label="经纬度">
        <mapCard @getAddress="getAddress"></mapCard>
      </el-form-item>

      <el-form-item prop="taskAddress" label="详细地址">
        <el-input v-model="form.taskAddress"></el-input>
      </el-form-item>

      <el-form-item prop="onSiteCommand" label="现场指挥">
        <el-select v-model="form.onSiteCommand" clearable filterable remote reserve-keyword placeholder="请输入关键词"
          :remote-method="remoteMethod" :loading="loading">
          <el-option v-for="item in nameOptions" :key="item.real_name" :label="item.real_name" :value="item.real_name">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item prop="onSiteSecretary" label="现场秘书">
        <el-select v-model="form.onSiteSecretary" clearable filterable remote reserve-keyword placeholder="请输入关键词"
          :remote-method="remoteMethod" :loading="loading">
          <el-option v-for="item in nameOptions" :key="item.real_name" :label="item.real_name" :value="item.real_name">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item prop="backstageSecretary" label="后台秘书">
        <el-select v-model="form.backstageSecretary" clearable filterable remote reserve-keyword placeholder="请输入关键词"
          :remote-method="remoteMethod" :loading="loading">
          <el-option v-for="item in nameOptions" :key="item.real_name" :label="item.real_name" :value="item.real_name">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item prop="startTime" label="开始时间">
        <el-date-picker v-model="form.startTime" value-format="yyyy-MM-dd hh:mm:ss" type="datetime"
          placeholder="选择日期时间">
        </el-date-picker>
      </el-form-item>
      <!-- <div>{{ form.startTime }}</div> -->
      <el-form-item prop="endTime" label="后台时间">
        <el-date-picker v-model="form.endTime" value-format="yyyy-MM-dd hh:mm:ss" type="datetime" placeholder="选择日期时间">
        </el-date-picker>
      </el-form-item>

      <el-form-item prop="taskStatus" label="任务状态">
        <el-radio-group v-model="form.taskStatus">
          <el-radio :label="0">未完成</el-radio>
          <el-radio :label="1">已完成</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item prop="cooperativeUnitsId" label="合作单位">
        <el-select v-model="form.cooperativeUnitsId">
          <el-option :label="item.name" :value="item.id" :key="item.id" v-for="item in coopers"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item prop="uav" label="无人机">
        <el-radio-group v-model="form.uav">
          <el-radio :label="0">无</el-radio>
          <el-radio :label="1">有</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item prop="dog" label="搜救犬">
        <el-radio-group v-model="form.dog">
          <el-radio :label="0">无</el-radio>
          <el-radio :label="1">有</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item prop="targetState" label="目标状态">
        <el-radio-group v-model="form.targetState">
          <el-radio label="A">A</el-radio>
          <el-radio label="B">B</el-radio>
          <el-radio label="C">C</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item prop="pub" label="公开">
        <el-radio-group v-model="form.pub">
          <el-radio :label="0">不公开</el-radio>
          <el-radio :label="1">公开</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item prop="taskSupports" label="任务内容">
        <Tiny v-model="form.taskSupports"></Tiny>
      </el-form-item>

      <el-form-item prop="taskInfo" label="任务详情">
        <Tiny v-model="form.taskInfo"></Tiny>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submit">立即保存</el-button>
        <el-button @click="close">返回</el-button>
      </el-form-item>

    </el-form>
  </div>
</template>
<script>
import { regionData } from 'element-china-area-data'
import mapCard from '@/components/map-card.vue'
let districts = []
districts = regionData.find(item => item.label == "江苏省").children.find(item => item.label == "南京市").children
districts.push({ value: "999999", label: "外市" })

import { allnames } from '@/api/member'
import { cooperList, taskEdit } from '@/api/task'
import { uploadImg } from '@/api/common';
import Tiny from "@/components/Tiny"
import { taskDetail } from '@/api/task'



export default {
  components: { mapCard, Tiny },
  data() {
    return {
      typeIds: [],
      form: {
        taskName: "",
        taskTypeId: "",
        taskCity: "南京市",
        taskDistrict: "",
        taskAddress: "",
        latitude: "",
        longitude: "",
        taskStatus: 1,
        uav: 0,
        dog: 0,
        targetState: "A",
        pub: 1,
        cover: "",
        onSiteCommand: "",
        onSiteSecretary: "",
        backstageSecretary: "",
        startTime: "",
        cooperativeUnitsId: "",
        taskSupports: "",
        taskInfo: ""
      },

      rules: {
        taskName: [{ required: true, trigger: "blur", message: "请输入" }],
        taskTypeId: [{ required: true, trigger: "blur", message: "请选择" }],
        onSiteCommand: [{ required: true, trigger: "blur", message: "请选择" }],
        taskDistrict: [{ required: true, trigger: "blur", message: "请选择" }],
      },
      options: [],
      districts,
      names: [],
      loading: false,
      nameOptions: [],
      coopers: [],
      imageUrl: ""
    }
  },
  methods: {
    recursion(data, arr, parentId) {
      data.forEach(item => {
        if (item.parentId === parentId) {
          arr.push(item)
          // 判断原数组中有parentId 是当前元素的id
          if (data.some(it => it.parentId === item.id)) {
            item.children = []
            this.recursion(data, item.children, item.id)
          }
        }
      })
    },
    handleTypeChange() {
      if (this.typeIds.length > 0) {
        this.form.taskTypeId = this.typeIds[this.typeIds.length - 1]
      }
    },
    getAddress(val) {
      this.form.taskAddress = val.address
      this.form.latitude = val.latitude
      this.form.longitude = val.longitude
    },
    getAllnames() {
      allnames().then(res => {
        console.log(res);
        this.names = res.data
      })
    },
    remoteMethod(query) {
      if (query !== '') {
        this.loading = true;
        setTimeout(() => {
          this.loading = false;
          this.nameOptions = this.names.filter(item => {
            return item.real_name.toLowerCase()
              .indexOf(query.toLowerCase()) > -1;
          });
        }, 100);
      } else {
        this.options = [];
      }
    },
    getCooperList() {
      cooperList().then(res => {
        this.coopers = res.data
      })
    },
    // handleCoverChange(file) {
    //   if (this.beforeAvatarUpload(file.raw)) {
    //     const formData = new FormData();
    //     console.log(formData, 'formData');
    //     console.log(file, '上传图片');

    //     formData.append("img", file.raw);

    //     uploadImg(formData).then(res => {
    //       console.log(res, "上传成功");

    //       this.form.cover = res.data.img
    //     })
    //   }
    // },
    // beforeAvatarUpload(file) {
    //   const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
    //   const isLt2M = file.size / 1024 / 1024;
    //   if (!isJPG) {
    //     this.$message.error('上传头像图片只能是 JPG，PNG 格式!');
    //   }
    //   if (!isLt2M) {
    //     this.$message.error('上传头像图片大小不能超过 1MB!');
    //   }
    //   return isJPG && isLt2M;
    // },

    handleAvatarSuccess(file) {
      // console.log(res, "上传成功");
      console.log(file, "上传文件");

      // 处理头像上传成功后的逻辑，设置 imageUrl 为上传文件的本地 URL
      this.form.cover = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      // 上传头像前的检查函数，验证文件是否为 JPG 格式且大小不超过 2MB
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      console.log(file, "上传文件1");

      if (!isJPG) {
        // 如果文件不是 JPG 格式，提示错误信息
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        // 如果文件大小超过 2MB，提示错误信息
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      // 返回检查结果，只有当文件是 JPG 格式且大小不超过 2MB 时才允许上传
      return isJPG && isLt2M;
    },

    submit() {
      this.$refs["form"].validate(flag => {
        if (flag) {
          taskEdit(this.form).then(res => {
            // console.log(res);
            this.$message({
              type: "success",
              message: "保存成功"
            })
            this.$router.push({
              path: "/task/index"
            })
          })
        }
      })
    },
    close() {
      this.$router.push({
        path: "/task/index"
      })
    },
    getDetail() {
      taskDetail({ id: this.$route.query.id }).then(res => {
        this.form = res.data
        // console.log(this.form);
        this.typeIds = res.data.taskTypeId
      })
    }
  },
  mounted() {
    this.recursion(this.$store.state.data.types, this.options, null)
    this.getAllnames()
    this.getCooperList()
    if (this.$route.query.id) {
      this.getDetail()
    }
  }
}
</script>
<style>
.el-form-item {
  padding-bottom: 10px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
